package com.ywx.yypicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywx.yypicturebackend.constant.UserConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import com.ywx.yypicturebackend.model.dto.user.UserQueryRequest;
import com.ywx.yypicturebackend.model.entity.User;
import com.ywx.yypicturebackend.model.enums.UserRoleEnum;
import com.ywx.yypicturebackend.model.vo.LoginUserVO;
import com.ywx.yypicturebackend.model.vo.UserVO;
import com.ywx.yypicturebackend.service.UserService;
import com.ywx.yypicturebackend.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ywx
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-05-09 10:51:06
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //1.判断参数是否合法
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码长度过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR, "两次密码输入不一致");

        //2.判断数据库中是否有该账户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = this.baseMapper.selectCount(queryWrapper);
        ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR, "账号重复");

        //3.对密码进行加密
        String encryptPassword = getEncryptPassword(userPassword);


        //4.存放在数据库中
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName(UserConstant.DEFAULT_USERNAME);
        user.setUserRole(UserRoleEnum.USER.getValue());

        boolean saveResult = this.save(user);

        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "注册失败,数据库错误");

        return user.getId();
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //1.判断参数是否合法
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4 || userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "账号或密码错误");

        //2.检验密码是否正确
        //获取加密后的密码
        String encryptPassword = getEncryptPassword(userPassword);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);

        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码错误");
        }
        //3.记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        return this.getLoginUserVo(user);
    }


    @Override
    public String getEncryptPassword(String password) {

        return DigestUtils.md5DigestAsHex((UserConstant.MD5_SALT + password).getBytes());
    }


    @Override
    public User getLoginUser(HttpServletRequest request) {
        //判断是否已经登录
        User user = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if(user == null || user.getId() == null){
            throw  new BusinessException(ErrorCode.NOT_LOGIN_ERROR);

        }

        //从数据库查询最新结果,如果要追求性能,可以直接返回上述结果

        User currentUser = this.getById(user.getId());
        if (currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        return currentUser;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        //判断是否已经登录
        HttpSession requestSession = request.getSession();
        Object attribute = requestSession.getAttribute(UserConstant.USER_LOGIN_STATE);
        if(attribute == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }


        requestSession.removeAttribute(UserConstant.USER_LOGIN_STATE);


        return true;
    }


    @Override
    public LoginUserVO getLoginUserVo(User user) {
        if (user == null)
            return null;

        LoginUserVO loginUserVo = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVo);

        return loginUserVo;
    }

    @Override
    public UserVO getUserVo(User user) {
        if (user == null)
            return null;

        UserVO userVo = new UserVO();
        BeanUtils.copyProperties(user,userVo);

        return userVo;
    }

    @Override
    public List<UserVO> getUserVoList(List<User> userList) {
        if (CollUtil.isEmpty(userList)){
            return new ArrayList<>();
        }

        return userList.stream().map(this::getUserVo).collect(Collectors.toList());

    }

    @Override
    public boolean isAdmin(User user) {

        return user!=null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {

        if (userQueryRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq(ObjectUtil.isNotNull(id),"id",id);
        userQueryWrapper.eq(ObjectUtil.isNotNull(userRole),"userRole",userRole);

        userQueryWrapper.like(ObjectUtil.isNotNull(userName),"userName",userName);
        userQueryWrapper.like(ObjectUtil.isNotNull(userAccount),"userAccount",userAccount);
        userQueryWrapper.like(ObjectUtil.isNotNull(userProfile),"userProfile",userProfile);
        userQueryWrapper.orderBy(ObjectUtil.isNotNull(sortField),sortOrder.equals("ascend"),sortField);




        return userQueryWrapper;

    }
}




